package com.browan.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.browan.demo.http.MeetingApi;
import com.browan.demo.http.MeetingReturned;
import com.browan.freeppmobile.jni.FreeppKit;

public class RegisterDialog extends Activity {
	private EditText mNumberEditText = null;
	private Button mRegisterBtn = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.register);
		
		this.setTitle("Register");
		
		mRegisterBtn = (Button) findViewById(R.id.register);
		mNumberEditText = (EditText) findViewById(R.id.number);
		
		mRegisterBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String number = mNumberEditText.getText().toString().trim();
				if(isE164Format(number)) {
					MeetingReturned returned = MeetingApi.getInstance().register(number);
					if(returned != null && returned.isSuccess) {
						FreeppKit.freeppId = returned.freeppid;
						FreeppKit.e164Number = number;
						FreeppKit.getInstance().saveAccount();
						
						RegisterDialog.this.setResult(1);
						RegisterDialog.this.finish();
					}
					else {
						RegisterDialog.this.setResult(0);
						RegisterDialog.this.finish();
					}
				}
				else {
					Toast toast = Toast.makeText(RegisterDialog.this, "请输入E164格式的号码，形如+8618600001234", Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
			}
		});
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		switch (keyCode)
		{
		case KeyEvent.KEYCODE_BACK:
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
	private boolean isE164Format(String src) 
	{
		return (src.startsWith("+") && (src.length() == 14));
	}
}
